package orgInfo

import (
	"fmt"
	"github.com/hyperledger/fabric-sdk-go/pkg/common/providers/fab"
	"github.com/hyperledger/fabric-sdk-go/pkg/fabsdk"
)

// 用户（普通用户、管理员）账本操作---用于账本底层查询操作 eg：根据id查询block

//  从Application结构体中搬过来--下面的方法需要改---应该是统计application中要查询的东西，在这边只写底层的
// 统计后需要完成如下四个方法：查询区块链信息、获取区块配置信息、根据区块号查询区块--改造为查询从i到j的区块、根据txid查询tx---改造为查询txid切片的交易

// GetBlockchainInfo 查询区块链信息
func (o *OrgInfo) GetBlockchainInfo(fabSDK *fabsdk.FabricSDK, channelID string, userName string) (*fab.BlockchainInfoResponse, error) {
	// 获取leClient
	leClient, err := o.CreatLedgerClient(fabSDK, channelID, userName)
	if err != nil {
		return nil, fmt.Errorf("GetBlockchainInfo err: %v", err)
	}
	// 查询信息
	info, err := leClient.QueryInfo()
	if err != nil {
		return nil, fmt.Errorf("failed to query: %v", err)
	}
	return info, nil
}

// GetConfigInfo 获取区块配置信息
func (o *OrgInfo) GetConfigInfo(fabSDK *fabsdk.FabricSDK, channelID string, userName string) (fab.ChannelCfg, error) {
	// 获取leClient
	leClient, err := o.CreatLedgerClient(fabSDK, channelID, userName)
	if err != nil {
		return nil, fmt.Errorf("GetConfigInfo err: %v", err)
	}
	// 查询信息
	info, err := leClient.QueryConfig()
	if err != nil {
		return nil, fmt.Errorf("failed to query: %v", err)
	}
	return info, nil
}

// GetBlockInfo 根据区块号为 startNum 到 endNum 的区块切片(升序)
func (o *OrgInfo) GetBlockInfo(fabSDK *fabsdk.FabricSDK, channelID string, userName string, startNum int, endNum int) ([]*Block, error) {
	// 获取leclient
	leClient, err := o.CreatLedgerClient(fabSDK, channelID, userName)
	if err != nil {
		return nil, fmt.Errorf("GetBlockInfo err: %v", err)
	}
	// 遍历查询区块
	var blocks []*Block
	for i := startNum; i <= endNum; i++ {
		block, err := QueryBlockByBlockNumber(leClient, int64(i))
		if err != nil {
			fmt.Println("GetBlockInfo err:", err)
			blocks = append(blocks, &Block{}) // 如果某个区块未查到则返回空的结构体
			continue
		}
		blocks = append(blocks, block)
	}
	return blocks, nil
}

// GetTxInfo 根据txid查询交易
func (o *OrgInfo) GetTxInfo(fabSDK *fabsdk.FabricSDK, channelID string, userName string, txids []string) ([]*Transaction, error) {
	// 获取leClient
	leClient, err := o.CreatLedgerClient(fabSDK, channelID, userName)
	if err != nil {
		return nil, fmt.Errorf("GetTxInfo err: %v", err)
	}
	//遍历查询
	var txs []*Transaction
	for _, txid := range txids {
		tx, err := QueryTxInfoByTxID(leClient, txid)
		if err != nil {
			fmt.Println("QueryTxInfoByTxID err:", err)
			txs = append(txs, &Transaction{}) // 如果某笔交易未查到则返回空的结构体
			continue
		}
		txs = append(txs, tx)
	}
	return txs, nil
}
